//
//  RadioPlay_info_ViewController.m
//  Leisure
//
//  Created by xalo on 16/7/4.
//  Copyright © 2016年 朱旭东. All rights reserved.
//

#import "RadioPlay_info_ViewController.h"

@interface RadioPlay_info_ViewController ()<UITableViewDelegate,UITableViewDataSource,playManagerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollVIew;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@property (weak, nonatomic) IBOutlet UIImageView *currimg;//唱片图像
@property (weak, nonatomic) IBOutlet UIView*backView;
//播放
@property (weak, nonatomic) IBOutlet UISlider *slider;//滑块
@property (weak, nonatomic) IBOutlet UIButton *LastMusic;//上一曲
@property (weak, nonatomic) IBOutlet UIButton *NextMusic;//下一曲
@property (weak, nonatomic) IBOutlet UIButton *paluseOrPlayMusic;//暂停或播放
//下载
@property (weak, nonatomic) IBOutlet UIButton *downLoadAction;
@property (weak, nonatomic) IBOutlet UIProgressView *progress;


@property(nonatomic,assign)NSInteger currentIndex;//记录当前正在播放的下标
@property(nonatomic,strong)UIView *greenView;

@end

@implementation RadioPlay_info_ViewController


//根据下表找到对应的cell
-(UITableViewCell *)fetchCellWithindex:(NSInteger)index{

    return [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
}


//重写dataSource的set方法
- (void)setDataSource:(NSMutableArray *)dataSource{
    if (_dataSource[0] != dataSource[0]) {
        self.currentIndex = -1;
        _dataSource = dataSource;
    }
}

- (UIView *)greenView
{
    if (!_greenView) {
        _greenView =[[UIView  alloc] initWithFrame:CGRectMake(kwidth-10, 0, 10, [self fetchCellWithindex:0].frame.size.height)] ;
        _greenView.backgroundColor = [UIColor  greenColor];
    }
    return _greenView;
}



//单利
+(instancetype)defaultManager{
    static RadioPlay_info_ViewController *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle= [[RadioPlay_info_ViewController alloc]initWithNibName:@"RadioPlay_info_ViewController" bundle:nil];
    });
    return handle;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets   =  NO;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"RadioPlayListCell" bundle:nil] forCellReuseIdentifier:@"RadioPlay_in_ViewController_cell"];
    
    //为防止第一首歌不能播放
    self.currentIndex = -1;
    
    //设置图片约束
    [self.currimg layoutIfNeeded];
    self.currimg.layer.cornerRadius = CGRectGetWidth(self.currimg.frame)/2;
    self.currimg.layer.masksToBounds  = YES;
    
    //设置图片背景图约束
    [self.backView layoutIfNeeded];
    self.backView.layer.cornerRadius = CGRectGetWidth(self.backView.frame)/2;
    self.backView.layer.masksToBounds  = YES;
    
    [PlayMusic  defaultManager].delegate = self;
    
    //设置WebView
    self.webView.backgroundColor = [UIColor clearColor];
    self.webView.opaque = NO;

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //为了防止点击同一首重新播放的情况的发生
    if (self.index != self.currentIndex) {
        self.currentIndex  = self.index;
        [self setPlayInfoWithIndex:self.currentIndex];
    }
}



#pragma mark  ------------实现协议方法 PlayManagerDelegate---------------
- (void)playManagerDelegateFetToTime:(NSString *)totalTime currenttime:(NSString *)currenTime progress:(CGFloat)progress{
    
    self.slider.value = progress;
    
    //图片旋转
    [UIView  animateWithDuration:0.1 animations:^{
        self.currimg.transform = CGAffineTransformRotate(self.currimg.transform, - M_PI/180);
    }];
}

- (void)playToNextMusic{
    [self NextMusicAction:nil];
}


#pragma mark -------------tableVIewDelegate-------------

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RadioPlayListCell *cell = [tableView  dequeueReusableCellWithIdentifier:@"RadioPlay_in_ViewController_cell" forIndexPath:indexPath];
    RadioListModel  *model =self.dataSource[indexPath.row];
    [cell setCellWithModel:model];
    
       return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

#pragma mark -------------- 按钮响应方法  --------------

//快进 快退
- (IBAction)sliderAction:(UISlider *)sender {
     [[PlayMusic defaultManager] playMusicWithSliderValue:sender.value];
}

// 上一曲
- (IBAction)lastMusicAction:(id)sender {
    if (self.currentIndex == 0) {
        self.currentIndex  = self.dataSource.count - 1;
    }else{
        self.currentIndex--;
    }
        [self setPlayInfoWithIndex:self.currentIndex];
 }

//下一曲
- (IBAction)NextMusicAction:(id)sender {
    if (self.currentIndex == self.dataSource.count - 1) {
        self.currentIndex = 0;
    }else {
        self.currentIndex++;
    }
    
    [self setPlayInfoWithIndex:self.currentIndex];
}

//设置界面信息
-(void)setPlayInfoWithIndex:(NSInteger)index{
    
    RadioListModel *model = self.dataSource[index];
    
    //子线程加载信息
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        [[PlayMusic defaultManager]prepareToPlayMusicWithUrl:model.musicUrl];
        
        [self.webView  loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:model.webview_url]]];
        
        //通过JS设置webView的背景色
//        [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#FF0000'"];
        
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.currimg sd_setImageWithURL:[NSURL URLWithString:model.imgUrl]];
            self.currimg.transform =  CGAffineTransformMakeRotation(0);
            [self.greenView removeFromSuperview];
            [[self fetchCellWithindex:index] addSubview:self.greenView];
            [self.tableView  reloadData];
        });
        
    });
}

//暂停或播放
- (IBAction)PaulseOrPalyMusicACtion:(id)sender {
    
    if ([[PlayMusic defaultManager]isPlaying] == NO) {
        [[PlayMusic defaultManager]playMusic];
    }else{
        [[PlayMusic defaultManager]pasuemusic];
    }

}

//下载事件
- (IBAction)downLoadAction:(id)sender {
    
    DownLoad *dowload = [[DownLoad alloc] initWithUrl:[self.dataSource[self.currentIndex] musicUrl]];
    
    [dowload startDownLoad];
    [dowload downLoading:^(long long bytesWritten, float progress) {
        
        //在主线程中刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            self.progress.progress  = progress / 100;
        });
        
    } didfinished:^(NSString *filePath, NSString *url) {
        
        
        //保存数据
        NSLog(@"%@",filePath);
       
    }];
    

}




@end
